﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xss.Configuration;
using System.Collections;

namespace Xss.Logging.Configuration
{
    public class LogConfigurationInterpreter : XmlConfigurationInterpreter
    {
        public IDictionary Settings { get; set; }

        protected override void ProcessXml(System.Xml.Linq.XDocument doc)
        {
            Settings = ParseInternal(doc.Root);
        }

        public override Core.IContextFactory BuildContextFactory()
        {
            return new LogContextFactory() { Settings = Settings };
        }

        /// <summary>
        /// 内部解析 
        /// </summary>
        /// <param name="xRoot"></param>
        /// <returns></returns>
        protected System.Collections.Specialized.HybridDictionary ParseInternal(System.Xml.Linq.XElement xRoot)
        {
            var config = new System.Collections.Specialized.HybridDictionary();
            var logger = xRoot.Element("logger");

            #region Type

            config["factory"] = Xml.XmlAttribute.Value<Type>(
                     logger,
                     "factory",
                     attr => { return Type.GetType(attr, true, true); },
                     typeof(Simple.LoggerFactory));

            config["logger"] = Xml.XmlAttribute.Value<Type>(
                     logger,
                     "type",
                     attr => { return Type.GetType(attr, true, true); },
                     typeof(Simple.Logger));

            #endregion

            #region Settings
            foreach (var x in logger.Elements("add"))
            {
                config[x.Attribute("key").Value] = x.Attribute("value").Value;
            }
            #endregion

            return config;
        }

        /// <summary>
        /// 默认Log配置信息
        /// </summary>
        public System.Collections.Specialized.HybridDictionary DefaultSetting
        {
            get
            {
                var config = new System.Collections.Specialized.HybridDictionary();
                config["factory"] = typeof(Simple.LoggerFactory);
                config["logger"] = typeof(Simple.Logger);
                return config;
            }
        }
    }
}
